package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.DepartmentDao;
import cn.yunyichina.provider.base.dao.DeptDao;
import cn.yunyichina.provider.base.dao.DoctorDao;
import cn.yunyichina.provider.base.entity.Department;
import cn.yunyichina.provider.base.entity.Dept;
import cn.yunyichina.provider.base.entity.Doctor;
import cn.yunyichina.provider.base.utils.IdCardUtils;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.base.Rule;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterDoctorsVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterDoctorsVoResponse;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterInfoVoResponse;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.swing.StringUIClientPropertyKey;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by JoeZ on 2016/9/20.
 */
@Service
public class DoctorServiceImpl {

    @Autowired
    private DoctorDao doctorDao;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static Logger log = LoggerFactory.getLogger(DoctorServiceImpl.class);

    @Resource
    private Properties yamlProperties;

    @Autowired
    private DepartmentDao departmentDao;

    /**
     * 医生列表查询
     *
     * @param data
     * @return
     */
    public Response listDoctor(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String hospitalId = maps.get("hospital_id");
        String branchCode = maps.get("branch_code");

        String page_num = maps.get("page_num");
        String page_size = maps.get("page_size");

        Doctor doctor = new Doctor();
        doctor.setHospitalId(hospitalId);
        doctor.setBranchCode(branchCode);
        doctor.setDelStatus(0);

        //查出总记录数
        long count = doctorDao.selectCount(doctor);
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(Integer.valueOf(page_num));
        pageInfo.setPageSize(Integer.valueOf(page_size));

        pageInfo.setTotal(count);
        pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
        List<Doctor> doctors = doctorDao.select(doctor, pageInfo);

        result.put("list", doctors);
        result.put("page_info", pageInfo);

        response.setResult(JsonUtils.toJsonString(result));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }


    /**
     * 医生列表条件查询
     *yyt.base.doctor.search
     * @param data
     * @return
     */
    public Response searchDoctor(String data) {

        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String deptId = maps.get("dept_id");
        String entryTime = maps.get("entry_time");
        String overTime = maps.get("over_time");
        String status = maps.get("status");
        String name = maps.get("name");
        String hospitalId = maps.get("hospital_id");

        String page_num = maps.get("page_num");
        String page_size = maps.get("page_size");

        Doctor doctor = new Doctor();
        doctor.setDelStatus(0);


        //条件搜索
        if (StringUtils.isNotBlank(deptId)) {
            doctor.setDepartmentId(deptId);
        }
        if (StringUtils.isNotBlank(status)) {
            doctor.setStatus(Integer.valueOf(status));
        }
        if (StringUtils.isNotBlank(name)) {
            doctor.setName(name);
        }
        if (StringUtils.isNotBlank(hospitalId)) {
            doctor.setHospitalId(hospitalId);
        }

        List<Doctor> doctors = null;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(Integer.valueOf(page_num));
        pageInfo.setPageSize(Integer.valueOf(page_size));

        if (StringUtils.isBlank(entryTime)) {

            //查出总记录数
            long count = doctorDao.selectCount(doctor);

            pageInfo.setTotal(count);
            pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());

            doctors = doctorDao.select(doctor, pageInfo);
        } else {
            //时间区间查询
            doctors = doctorDao.selectFindDoctor(pageInfo, entryTime, overTime);
            pageInfo.setTotal(Long.valueOf(doctors.size()));

        }

        if("stszxyy".equals(doctors.get(0).getHospitalCode())){
            RegisterDoctorsVo doctorsVo = new RegisterDoctorsVo();
            doctorsVo.setHospitalCode(doctors.get(0).getHospitalCode());
            ResCommon<List<RegisterDoctorsVoResponse>> infoResponse = HisifaceService.getHisifaceClient().getRegisterDoctors(doctorsVo);
            log.info("listRegDoctorSource,call hisiface getRegisterInfo,request={},response={}",
                    JSONObject.toJSONString(doctorsVo),JSONObject.toJSONString(infoResponse));
            if (ResCommon.SUCCESS_CODE.equals(infoResponse.getResultCode())) {
                List<RegisterDoctorsVoResponse> doctorsVoResponseList = infoResponse.getResult();
                if(doctorsVoResponseList != null && doctorsVoResponseList.size() > 0){
                    for(Doctor doc :doctors){
                        for(RegisterDoctorsVoResponse docHis:doctorsVoResponseList){
                            if(doc.getDoctorCode().equals(docHis.getDoctorCode())){
                                doc.setDisc(docHis.getDoctorIntroduction());
//                                doc.setTitle(docHis.getDoctorTitle());
                                if(StringUtils.isNotBlank(docHis.getClinicTime())) {
                                    doc.setClinicTime(docHis.getClinicTime());
                                }
                            }
                        }
                    }
                }
            }
        }

        result.put("list", doctors);
        result.put("page_info", pageInfo);

        response.setResult(JsonUtils.toJsonString(result));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }


    /**
     * 新增医生
     *
     * @param data
     * @return
     */
    public Response addDoctor(String data) {

        Response response = new Response();

        Doctor doctor = JsonUtils.parseObject(data, Doctor.class);
        doctor.setCreatedTime(simpleDateFormat.format(new Date()));
        doctor.setUpdateTime(simpleDateFormat.format(new Date()));

        if (StringUtils.isBlank(doctor.getEntryTime())) {
            doctor.setEntryTime(null);
        }
        if (StringUtils.isBlank(doctor.getRetirementTime())) {
            doctor.setRetirementTime(null);
        }
        if (StringUtils.isBlank(doctor.getDepartureTime())) {
            doctor.setDepartureTime(null);
        }
        if (StringUtils.isBlank(doctor.getDeathTime())) {
            doctor.setDeathTime(null);
        }
        if (StringUtils.isBlank(doctor.getLossTime())) {
            doctor.setLossTime(null);
        }

        if (StringUtils.isNotBlank(doctor.getIdNo())) {
            //根据身份证获取性别和生日
            String gender = IdCardUtils.getGenderByIdCard(doctor.getIdNo());
            if ("F".equals(gender)) {
                doctor.setSex(2);
            } else {
                doctor.setSex(1);
            }

            String birth = IdCardUtils.getBirthByIdCard(doctor.getIdNo());
            doctor.setBirth(birth);
        }


        doctor.setId(PKGenerator.generateId());
        doctorDao.insert(doctor);

        response.setResultCodeAndMessage("0", "添加成功!");
        response.setResult(JsonUtils.toJsonString(doctor));

        return response;

    }


    /**
     * 修改医生
     *
     * @param data
     * @return
     */
    public Response updateDoctor(String data) {

        Response response = new Response();

        Doctor doctor = JsonUtils.parseObject(data, Doctor.class);

        if (StringUtils.isBlank(doctor.getEntryTime())) {
            doctor.setEntryTime(null);
        }
        if (StringUtils.isBlank(doctor.getRetirementTime())) {
            doctor.setRetirementTime(null);
        }
        if (StringUtils.isBlank(doctor.getDepartureTime())) {
            doctor.setDepartureTime(null);
        }
        if (StringUtils.isBlank(doctor.getDeathTime())) {
            doctor.setDeathTime(null);
        }
        if (StringUtils.isBlank(doctor.getLossTime())) {
            doctor.setLossTime(null);
        }


        if (StringUtils.isNotBlank(doctor.getIdNo())) {
            //根据身份证获取性别和生日
            String gender = IdCardUtils.getGenderByIdCard(doctor.getIdNo());
            if ("F".equals(gender)) {
                doctor.setSex(2);
            } else {
                doctor.setSex(1);
            }

            String birth = IdCardUtils.getBirthByIdCard(doctor.getIdNo());
            doctor.setBirth(birth);
        }

        doctor.setUpdateTime(simpleDateFormat.format(new Date()));

        doctorDao.update(doctor);
        response.setResultCodeAndMessage("0", "修改成功!");
        response.setResult(JsonUtils.toJsonString(doctor));

        return response;

    }


    /**
     * 删除医生
     *
     * @param data
     * @return
     */
    public Response deleteDoctor(String data) {

        Response response = new Response();

        Doctor exDoctor = JsonUtils.parseObject(data, Doctor.class);
        Doctor doctor = doctorDao.selectById(exDoctor.getId());

        doctor.setDelStatus(1);
        doctorDao.update(doctor);

        response.setResultCodeAndMessage("0", "删除成功!");
        response.setResult(JsonUtils.toJsonString(doctor));

        return response;

    }


    /**
     * 根据ID查询医生
     *
     * @param data
     * @return
     */
    public Response findDoctor(String data) {
        Response response = new Response();
        Doctor doctor = null;

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String code = maps.get("code");
        String doctorId = maps.get("id");
        String hospitalCode = maps.get("hospitalCode");

        String getDoctorKey = "";
        String getDoctorValue = "";
        if (StringUtils.isNotBlank(code)) {
            getDoctorKey = hospitalCode + "_" + code;
            getDoctorValue = CacheService.getCacheClient().getDoctorCache(getDoctorKey);

            doctor = new Doctor();
            doctor.setDoctorCode(code);
            doctor.setHospitalCode(hospitalCode);
            doctor.setDelStatus(0);
        } else {
            getDoctorKey = doctorId;
            getDoctorValue = CacheService.getCacheClient().getDoctorCache(getDoctorKey);

            doctor = new Doctor();
            doctor.setId(doctorId);
            doctor.setDelStatus(0);
        }

        if (!StringUtils.isBlank(getDoctorValue)) {
            log.info("DoctorService.findDoctor.命中缓存->key:" + getDoctorKey + ",value:" + getDoctorValue);
            Doctor doctorCache = JSON.parseObject(getDoctorValue, Doctor.class);
            response.setResult(JsonUtils.toJsonString(doctorCache));
            response.setResultCodeAndMessage("0", "查询成功!");
            return response;
        }

        List<Doctor> select = doctorDao.select(doctor);
        if (select.size() < 1) {
            response.setResult(null);
            response.setResultCodeAndMessage("1001", "查无医生!");
        } else {
            log.info("DoctorSize: " + select.size());
            doctor = select.get(0);

            //设置医生信息到缓存上
            String key = "";
            if (StringUtils.isNotBlank(code)) {
                key = hospitalCode + "_" + code;
            } else {
                key = doctorId;
            }
            CacheService.getCacheClient().setDoctorCache(key, JSON.toJSONString(doctor));

            response.setResult(JsonUtils.toJsonString(doctor));
            response.setResultCodeAndMessage("0", "查询成功!");
        }
        return response;
    }

    /**
     * 重新加载医生信息到缓存 yyt.base.doctor.reload
     *
     * @param data
     * @return
     */
    public Response reloadDoctor(String data) {
        Response response = new Response();

        Doctor wheres = new Doctor();
        Map<String, String> maps = new HashMap<String, String>(1);
        if (!StringUtils.isBlank(data)) {
            maps = JsonUtils.parseObject(data, Map.class);
            if (maps.containsKey("hospital_code")) {
                wheres.setHospitalCode(maps.get("hospital_code"));
            }
        }
        wheres.setDelStatus(0);
        List<Doctor> doctors = doctorDao.select(wheres);
        
        for(Doctor doctor:doctors){
            String doctorHospitalCodeKey = doctor.getHospitalCode() + "_" + doctor.getDoctorCode();
            String doctorIdKey=doctor.getId();
            CacheService.getCacheClient().setDoctorCache(doctorHospitalCodeKey, JSON.toJSONString(doctor));
            CacheService.getCacheClient().setDoctorCache(doctorIdKey, JSON.toJSONString(doctor));
        }
        response.setResultCodeAndMessage("0", "更新缓存成功[入参:" + data + ",成功更新医生信息:[" + doctors.size() + "条]]!");
        return response;
    }


    /**
     * 搜索科室和医生
     *yyt.base.doctor.and.dept.search
     * @param data {"name":"","hospital_code":"stszxyy"}
     * @return {"result":"{\"dept\":[],\"doctor\":[]}","result_code":"0","result_message":"查询成功!","success":true}
     */
    public Response searchDoctorAndDept(String data) {
        Response response = new Response();
        Map<String, Object> result = new HashMap<>();

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String name = maps.get("name");
        String hospitalCode = maps.get("hospital_code");

        if(StringUtils.isBlank(name) || StringUtils.isBlank(hospitalCode)){
            response.setResultCodeAndMessage("1001","入参name和hospital_code不能为空");
            return response;
        }

        Doctor doctor = new Doctor();
        doctor.setDelStatus(0);
        doctor.setName(name);
        doctor.setHospitalCode(hospitalCode);

        List<Doctor> doctors = doctorDao.select(doctor);

        for(Doctor doc :doctors){
            Department dept = departmentDao.selectById(doc.getDepartmentId());
            if(dept != null) {
                doc.setDeptCode(dept.getDeptCode());
            }
        }
        result.put("doctor", doctors);

        //搜科室
        Department dept = new Department();
        dept.setName(name);
        dept.setHospitalCode(hospitalCode);
        List<Department> deptList = departmentDao.select(dept);
        result.put("dept", deptList);

        String calendarDays  = getRule(hospitalCode,"calendarDaysType","7");
        result.put("calendar_days",calendarDays);

        response.setResult(JsonUtils.toJsonString(result));
        response.setResultCodeAndMessage("0", "查询成功!");

        return response;

    }

    public static String getRule(String hospitalCode,String attributeName,String defaultValue){
//        String cacheValue = CacheService.getGlobalKey(CacheConstant.CACHE_REGISTER_MODULE,CacheConstant.CACHE_REGISTER_RULE,hospitalCode);
//        if(StringUtils.isBlank(cacheValue)) {
//            logger.info("请先设置规则到缓存中:" + hospitalCode);
//            return defaultValue;
//        }
//
//
//        List<Rule> ruleList = JsonUtils.parseArray(cacheValue,Rule.class);
//        for(Rule rule : ruleList){
//            if(attributeName.equals(rule.getAttributeName())){
//                value = rule.getAttributeProperties();//单位：分钟
//                break;
//            }
//        }
        String value = null;
        Map<String,String> ruleMap = new HashMap<String,String>();
        ruleMap.put("attribute_name" , attributeName);
        ruleMap.put("org_code" , hospitalCode);
        Response ruleResp = BaseService.callHumpFromInternal("yyt.base.rule.select", JSON.toJSONString(ruleMap));

        if("0".equals(ruleResp.getResultCode())){
            Rule rule=JsonUtils.parseObject(ruleResp.getResult(), Rule.class);
            if(rule != null && attributeName.equals(rule.getAttributeName())){
                value = rule.getAttributeProperties();
            }
        }

        if(StringUtils.isBlank(value)){
            value = defaultValue;
        }
        return value;
    }

}
